package top.lgd.service.person;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lgd.base.LgdConstants;
import top.lgd.enums.AccountOpTypeEnum;
import top.lgd.mapper.person.SalaryMapper;
import top.lgd.pojo.entity.person.Account;
import top.lgd.pojo.entity.person.Salary;
import top.lgd.pojo.req.person.AccountOpReq;
import top.lgd.utils.DateUtils;
import top.lgd.utils.NumberUtils;

import java.math.BigDecimal;

/**
 * @author YYJ
 * @version 1.0
 */
@Service
public class SalaryService extends ServiceImpl<SalaryMapper, Salary> implements IService<Salary> {

    @Autowired
    private AccountService accountService;

    @Transactional(rollbackFor = Exception.class)
    public boolean addAndFlow(Salary salary) {
        if (salary.getAccumulationFund().compareTo(BigDecimal.ZERO) > 0) {
            salary.setSalaryMonth(DateUtils.getMonth(salary.getSalaryDate()));
            salary.setRemark(salary.getSalaryMonth() + " 工资收入");
        } else {
            salary.setSalaryMonth(DateUtils.getYear(salary.getSalaryDate()));
            salary.setRemark(salary.getSalaryMonth() + " 年一次性工资");
        }

        BigDecimal beforeTax = NumberUtils.add(salary.getBaseIn(),
                salary.getFestivalFee(),
                salary.getWelfare(),
                salary.getOtherIn());
        BigDecimal afterTax = NumberUtils.sub(beforeTax,
                salary.getAccumulationFund(),
                salary.getSocialSecurity(),
                salary.getOtherOut(),
                salary.getTax());
        salary.setBeforeTax(beforeTax);
        salary.setAfterTax(afterTax);
        Account account = accountService.queryAccount(LgdConstants.PERSON_ACCOUNT_SWAP_ID);
        AccountOpReq accountOpReq = new AccountOpReq();
        accountOpReq.setOpAmount(afterTax);
        accountOpReq.setOpType(AccountOpTypeEnum.salary.name());
        accountOpReq.setRemark(salary.getRemark());
        accountService.updateAccountAndFlow(account, accountOpReq);
        return save(salary);
    }
}
